<!--
  用气详情
  options: {
    meterId: 必传参数
    month: 当前月份必传参数
  }
-->

<template>
  <div class="candlestick-wrapper">
    <div class="chart-wrap">
      <div class="top-box">
        <Button type="primary" @click="createCurve">生成曲线</Button>
        <Button type="warning" @click="handleHistoryClick" style="margin-left:10px">历史用气量</Button>
        <Button type="info" @click="handleMeterDetail" style="margin-left:10px">表具详情</Button>
      </div>
      <div class="bottom-box">
        <e-candlestick
          :id="id + '-candlestick'"
          :chartData="canlestickData"
          @q-click="candlestickClickHandle"
          @q-datazoom="candlestickDatazoom"
        />
        <div class="no-data" v-show="showNoData">暂无数据</div>
      </div>
    </div>
    <Modal
      v-model="showLineByDayModel"
      title="一天抄表读数"
      @on-cancel="onElineByDayModalCancel"
      width="96%"
      :styles="{ top: '30px', height: '85%' }"
    >
      <e-line :modal="true" :id="id + '-day'" :chartData="lineDataByDay" @q-click="zhexianDayClickHandle" />
      <div class="no-data" v-show="showNoDataByDay">暂无数据</div>
      <div slot="footer">
        <Button @click="onElineByDayModalCancel" ghost>关闭</Button>
      </div>
    </Modal>
    <Modal
      key="zhexiantime"
      v-model="showLineByTimeModel"
      title="时间段抄表读数"
      @on-cancel="onElineByTimeModalCancel"
      width="96%"
      :styles="{ top: '30px', height: '85%' }"
    >
      <e-line :modal="true" :id="id + '-time'" :chartData="lineDataByTime" />
      <div class="no-data" v-show="noDataByHours">暂无数据</div>
      <div slot="footer">
        <Button @click="onElineByTimeModalCancel" ghost>关闭</Button>
      </div>
    </Modal>
    <!-- 表具详情 -->
    <Modal
      v-model="showMeterAndUserInfo"
      :title="currentMeterId + ' 表具详情'"
      @on-cancel="handleMeterAndUserInfoClose"
      width="96%"
      :styles="{ top: '30px', height: '85%' }"
    >
      <div
        id="meterAndUserInfo"
        :is="userAndMeterInfoTpl"
        :currentMeterId="currentMeterId"
        :content="meterAndUserInfo"
      ></div>
      <div slot="footer">
        <Button @click="handleMeterAndUserInfoClose" ghost>关闭</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import { concat, each, head, last, merge, isEmpty, isArray } from 'lodash'
import { nanoid } from 'nanoid'
import { getCandlestickData, getElineByDay, getElineByHours, fetchHistoryUseGas } from '@/api/gasConsumptionDetail'
import { getMeterAndUserInfo } from '@/api/meterDetail'
import { eLineOptions, eCandlestickOptions } from './chartOptions/index'

export default {
  name: 'gasConsumptionDetail',
  components: {
    ECandlestick: () => import('@/commons/charts/ECandlestick'),
    ELine: () => import('@/commons/charts/ELine'),
    UserAndMeterDetailETree: () => import('@/commons/UserAndMeterDetailETree')
  },
  props: {
    options: {
      type: Object
    },
    id: {
      type: String,
      default: nanoid()
    }
  },
  data() {
    return {
      showLineByDayModel: false,
      showLineByTimeModel: false,
      canlestickData: null, // k线图数据
      lineDataByDay: null, // 一天抄表周期
      lineDataByTime: null, // 一小时抄表周期
      hasCandlestickRequest: true, // k线图请求标识
      currentDate: null, // 当前日期
      showNoDataByDay: false,
      showNoData: false,
      noDataByHours: false,
      showMeterAndUserInfo: false, // 表具详情弹框显示、隐藏
      userAndMeterInfoTpl: null,
      meterAndUserInfo: null
    }
  },
  computed: {
    currentMeterId() {
      return this.options.meterId
    }
  },
  mounted() {
    const { month } = this.options
    this.currentDate = month
    this.fetchCandlestickData()
  },
  methods: {
    /**
     * desc: 显示加载loading
     * param {type}
     * return: void
     */
    showFetchLoading() {
      this.$Spin.show({
        render: h => {
          return h('div', [
            h('Icon', {
              class: 'spin-icon-load',
              props: {
                type: 'ios-loading',
                size: 20
              }
            }),
            h('div', '图表生成中...')
          ])
        }
      })
    },
    /**
     * desc: 隐藏请求loading
     * param {type}
     * return: void
     */
    hideFetchLoading() {
      this.$Spin.hide()
    },
    /**
     * desc: 关闭一天抄表周期读数模态框
     * param {type}
     * return: void
     */
    onElineByDayModalCancel() {
      this.showNoDataByDay = false
      this.showLineByDayModel = false
      this.lineDataByDay = null
    },
    /**
     * desc: 关闭一小时抄表周期读数模态框
     * param {type}
     * return: void
     */
    onElineByTimeModalCancel() {
      this.noDataByHours = false
      this.showLineByTimeModel = false
      this.lineDataByTime = null
    },
    /**
     * @msg: 指数图缩放
     * @param {type}
     * @return:
     */
    candlestickDatazoom(data = {}, chart) {
      if (!this.hasCandlestickRequest) return
      const { batch = [] } = data
      if (batch[0].start === 0 && batch[0].end === 100) {
        this.currentDate = dayjs(this.currentDate)
          .subtract(1, 'month')
          .format('YYYY-MM')
        this.showFetchLoading()
        this.$nextTick(() => {
          this.fetchCandlestickData()
        })
      }
    },
    /**
     * @msg: 指数图数据
     * @param {type}
     * @return:
     */
    modifyCandlestickData(rawData = []) {
      let xAixisList = []
      let values = []
      const actualGas = []
      const markPointData = []
      each(rawData, item => {
        const [first, one, two, three, four, five] = item
        xAixisList.push(first)
        let color0 = '#ec0000'
        let borderColor0 = '#8A0000'
        let color = '#00da3c'
        let borderColor = '#008F28'
        const lastItem = last(item)
        if (lastItem) {
          color0 = '#ff9900'
          borderColor0 = '#ff9900'
          color = '#ff9900'
          borderColor = '#ff9900'
          markPointData.push({
            name: first,
            value: two,
            coord: [first, two],
            itemStyle: {
              color: '#ff9900'
            }
          })
        }
        if (five < 0) {
          color0 = '#ed141e'
          borderColor0 = '#ed141e'
          color = '#ed141e'
          borderColor = '#ed141e'
        }
        values.push({
          name: first,
          value: [one, two, four, three],
          itemStyle: {
            color,
            borderColor,
            borderColor0,
            color0
          }
        })
        actualGas.push(five)
      })

      return {
        xAixisList,
        values: {
          data: values,
          markPointData
        },
        actualGas
      }
    },
    /**
     * @msg: 获取默认日期
     * @param {type}
     * @return:
     */
    getDefaultDate(list = []) {
      const _fList = head(list)
      if (isArray(_fList) && _fList[0]) {
        this.currentDate = dayjs(_fList[0])
      }
    },
    /**
     * @msg: 获取K线图数据
     * @param {type}
     * @return:
     */
    fetchCandlestickData() {
      const { meterId } = this.options
      this.showFetchLoading()
      getCandlestickData({
        meterId,
        month: this.currentDate
      })
        .then(res => {
          this.$Spin.hide()
          if (!this.hasCandlestickRequest) return
          if (res.date && res.date.length > 0) {
            this.getDefaultDate(res.date)
            const { xAixisList, values = {}, actualGas } = this.modifyCandlestickData(res.date)
            let _currentCanleData = null
            if (!isEmpty(this.canlestickData)) {
              _currentCanleData = this.canlestickData
            } else {
              _currentCanleData = {
                xAxis: {
                  data: []
                },
                series: [
                  {
                    data: [],
                    markPoint: {
                      data: []
                    }
                  },
                  {
                    data: []
                  }
                ]
              }
            }
            const {
              xAxis: { data = [] },
              series = []
            } = _currentCanleData
            this.canlestickData = merge({}, eCandlestickOptions, {
              xAxis: {
                data: concat(xAixisList, data || [])
              },
              series: [
                {
                  data: concat(values.data, series[0] ? series[0].data : []),
                  markPoint: {
                    data: concat(values.markPointData, series[0].markPoint ? series[0].markPoint.data : [])
                  }
                },
                {
                  data: concat(actualGas, series[1] ? series[1].data : [])
                }
              ]
            })
          } else {
            this.hasCandlestickRequest = false
            const { canlestickData } = this
            if (!canlestickData || canlestickData.series.length === 0) {
              this.showNoData = true
            }
          }
        })
        .finally(() => {
          this.hideFetchLoading()
        })
    },
    /**
     * @msg: 每天抄表周期数据整理
     * @param {type}
     * @return:
     */
    modifyElineByDayData(data) {
      const _serList = []
      const _xAxisList = []
      each(data, item => {
        const { hour, usage } = item
        _serList.push({
          name: hour,
          value: usage,
          hour
        })
        _xAxisList.push(hour)
      })

      this.lineDataByDay = merge({}, eLineOptions, {
        xAxis: {
          data: _xAxisList
        },
        series: [
          {
            data: _serList
          }
        ]
      })
    },
    /**
     * @msg: 获取每天的抄表周期详情
     * @param {type}
     * @return:
     */
    fetchElineDataByDay(days) {
      this.currentZhishuDate = days
      const { meterId } = this.options
      this.showLineByDayModel = true
      this.showFetchLoading()
      getElineByDay({
        meterId,
        days
      })
        .then(res => {
          if (res.date && res.date.length >= 0) {
            this.modifyElineByDayData(res.date)
          } else {
            this.showNoDataByDay = true
          }
        })
        .finally(() => {
          this.hideFetchLoading()
        })
    },
    /**
     * @msg: 每小时抄表周期数据整理
     * @param {type}
     * @return:
     */
    modifyELineByTimeData(data) {
      const _serList = []
      const _xAxisList = []
      each(data, item => {
        const { collectDataTime, collectValue } = item
        _serList.push({
          name: collectDataTime,
          value: collectValue
        })
        _xAxisList.push(collectDataTime)
      })
      this.lineDataByTime = merge({}, eLineOptions, {
        xAxis: {
          data: _xAxisList
        },
        series: [
          {
            data: _serList
          }
        ]
      })
    },
    /**
     * @msg: 获取每小时的抄表周期详情
     * @param {type}
     * @return:
     */
    fetchElineDataByTime(collectDataTime) {
      const { meterId } = this.options
      this.showLineByTimeModel = true
      this.showFetchLoading()
      getElineByHours({
        meterId,
        collectDataTime
      })
        .then(res => {
          if (res.date && res.date.length >= 0) {
            this.modifyELineByTimeData(res.date)
          } else {
            this.noDataByHours = true
          }
        })
        .finally(() => {
          this.hideFetchLoading()
        })
    },
    /**
     * @msg: 点击k线图
     * @param {type}
     * @return:
     */
    candlestickClickHandle(data) {
      if (data.seriesType !== 'line') {
        this.fetchElineDataByDay(data.name)
      }
    },
    /**
     * @msg: 点击一天抄表周期读数
     * @param {type}
     * @return:
     */
    zhexianDayClickHandle(params = {}) {
      const { data = {} } = params
      const { hour } = data
      const date = this.currentZhishuDate + ' ' + hour
      const retData = dayjs(date).format('YYYY-MM-DD HH')

      this.fetchElineDataByTime(retData)
    },
    /**
     * @msg: 生成曲线
     * @param {type}
     * @return:
     */
    createCurve() {
      const { series } = this.canlestickData
      const { data = [], name } = series[0]
      const firstList = []
      const twoList = []
      each(data, item => {
        const { value } = item
        firstList.push({
          name,
          value: value[2]
        })
        twoList.push({
          name,
          value: value[3]
        })
      })

      this.$set(this.canlestickData.series, 2, {
        ...series[2],
        data: firstList
      })
      this.$set(this.canlestickData.series, 3, {
        ...series[3],
        data: twoList
      })
    },
    /**
     * desc: 点击历史用气量
     * param {type}
     * return {type} void
     */
    handleHistoryClick() {
      const { meterId } = this.options
      this.showFetchLoading()
      fetchHistoryUseGas({
        meterId,
        days: 368
      })
        .then(res => {
          this.hasCandlestickRequest = false
          const { code, date } = res
          if (code === 200 && date) {
            const { xAixisList, values = {}, actualGas } = this.modifyCandlestickData(date)
            this.canlestickData = merge({}, eCandlestickOptions, {
              dataZoom: [{
                start: 0
              }, {
                start: 0
              }],
              xAxis: {
                data: xAixisList
              },
              series: [
                {
                  data: values.data,
                  markPoint: {
                    data: values.markPointData
                  }
                },
                {
                  data: actualGas
                }
              ]
            })
          }
        })
        .finally(() => {
          this.hideFetchLoading()
        })
    },
    /**
     * desc: 请求表具详情信息
     * param {type}
     * return: void
     */
    fetchMeterAndUserInfo() {
      if (!this.currentMeterId) {
        return this.$Notice.warning({
          title: '操作提示',
          desc: '没有可操作的数据'
        })
      }
      getMeterAndUserInfo(this.currentMeterId).then(res => {
        if (res.date) {
          this.meterAndUserInfo = res.date
          this.userAndMeterInfoTpl = 'UserAndMeterDetailETree'
          this.showMeterAndUserInfo = true
        }
      })
    },
    handleMeterDetail() {
      this.fetchMeterAndUserInfo()
    },
    handleMeterAndUserInfoClose() {
      this.showMeterAndUserInfo = false
      this.userAndMeterInfoTpl = null
    }
  }
}
</script>
<style lang="less" scoped>
@import './index.less';
</style>
